package name.suray.andrey;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XML implements IParser {
	
	public Map<String,String> parse() throws IOException{
		
		System.out.println("In XML.parse()...");
		final Map<String,String> map = new HashMap<String,String>();
		 
		try {
			
		 	SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser saxParser = factory.newSAXParser();
			
			DefaultHandler myHandler = new DefaultHandler() {
				String current = "";
					
				@Override
				public void startElement(String namespaceURI, String localName, 
						String qName, Attributes atts) throws SAXException {
					current = qName; 
				}
							
				@Override
				public void endElement(String namespaceURI, String localName, 
						String qName) throws SAXException {
					current = "";
				}
				
				@Override
				public void characters(char[] ch, int start, 
						int length) throws SAXException {
					if (current.equals("class")) {
						map.put("class",new String(ch, start, length));
						System.out.println(map.get("class"));
					}
					
					if (current.equals("field1")) {
						map.put("field1",new String(ch, start, length));
						System.out.println(map.get("field1"));
					}
					
					if (current.equals("field2")) {
						map.put("field2",new String(ch, start, length));
						System.out.println(map.get("field2"));
					}
					
					if (current.equals("field3")) {
						map.put("field3",new String(ch, start, length));
						System.out.println(map.get("field3"));
					}  
					
				}//end of characters
				
				@Override
				public void endDocument() {
				  System.out.println("Stop parse XML...");
				}
				
			};// end of handler
			
			saxParser.parse(new File("D:\\config.xml"), myHandler);
			
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}		
		
		boolean flag = Character.isUpperCase( map.get("class").charAt(0) );
		if(flag && map.get("class") != null && map.get("field1") != null 
			&& map.get("field2") != null & map.get("field3") != null){
			return map;			
		}else throw new IOException("Invalid config file.");
		
   }//end of parse	
}//end of class XML